package com.internship.controller;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import net.sf.json.JSONObject;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

import com.internship.model.Bjdmb;
import com.internship.model.DepartmentInfo;
import com.internship.model.Paper;
import com.internship.model.ProfessionInfo;
import com.internship.model.StudentInfo;
import com.internship.model.Thesis;
import com.internship.page.Page;
import com.internship.service.BjdmbService;
import com.internship.service.Const;
import com.internship.service.DepartmentInfoService;
import com.internship.service.FileUpload;
import com.internship.service.JobStudentService;
import com.internship.service.ThesisService;
import com.internship.service.ProfessionInfoService;
import com.internship.service.StudentInfoService;
import com.internship.util.StringUtil;


@Controller
@RequestMapping("thesis")
public class ThesisController {
	private final Logger logger = Logger.getLogger(ThesisController.class);
	
	@Autowired
	private ProfessionInfoService professionInfoService;
	@Autowired
	private DepartmentInfoService 	departmentInfoService;
	@Autowired
	private BjdmbService 	bjdmbService;
	@Autowired
	private ThesisService 	thesisService;
	@Autowired
	private StudentInfoService 	studentInfoService;
	public static HttpSession getSession() {
		HttpSession session = null;
		try {
			session = getRequest().getSession();
		} catch (Exception e) {
		}
		return session;
	}

	public static HttpServletRequest getRequest() {
		ServletRequestAttributes attrs = (ServletRequestAttributes) RequestContextHolder
				.getRequestAttributes();
		return attrs.getRequest();
	}
	private void clearSession() {
		getSession().invalidate();
	}
	/**?
	 * 学生毕业论文列表
	 * @return
	 */
	@RequestMapping("/thesis_list.do")
	public ModelAndView getPaperList() {
		return getPaperList(null,null,null,null,null,1);
	}
	private List<DepartmentInfo>  departmentInfoList = null;
	private List<ProfessionInfo>  professionInfoList = null;
	private List<Bjdmb>  bjdmbList = null;
	@RequestMapping("/thesis_page_list.do")
	public ModelAndView getPaperList(@RequestParam String studentName,@RequestParam String XY,@RequestParam String ZYDM,@RequestParam String XZB,@RequestParam String DQSZJ,@RequestParam int pageNumber) {
		ModelAndView mv = new ModelAndView("thesis_list");
		HttpSession session = getSession();
		try {
			if (String.valueOf(session.getAttribute(Const.USER_ROLE)).equals("2")||String.valueOf(session.getAttribute(Const.USER_ROLE)).equals("1")) {
				this.departmentInfoList = departmentInfoService.getDepartmentInfoList();
				if(XY==null || "".equals(XY.trim())){
					this.professionInfoList = professionInfoService.getProfessionInfoList();
					this.bjdmbList = bjdmbService.getBjdmbList();
				}else {
					DepartmentInfo departmentInfo=	departmentInfoService.getDepartmentInfo(XY);
					if (departmentInfo!=null) {
						this.professionInfoList = professionInfoService.getProfessionInfo(departmentInfo.getXYDM());
						if(ZYDM!=null){
							this.bjdmbList = bjdmbService.getBjdmb(departmentInfo.getXYDM(),ZYDM);
						}else {
							this.bjdmbList = bjdmbService.getBjdmb(departmentInfo.getXYDM(),null);	
						}
					}
				}
				mv.addObject("XY", XY);
				mv.addObject("ZYDM", ZYDM);
				mv.addObject("XZB", XZB);
				mv.addObject("departmentInfoList",departmentInfoList);
				mv.addObject("professionInfoList",professionInfoList);
				mv.addObject("bjdmbList",bjdmbList);
				Page<Thesis> pageList = thesisService.getThesisList(studentName, XY, ZYDM, XZB, DQSZJ, pageNumber);
				mv.addObject("currentPage", pageNumber);
				mv.addObject("totalPage", pageList.getTotalPage());
				mv.addObject("totalCount", pageList.getTotalCount());
				mv.addObject("paperList", pageList.getResultList());
			}else if(String.valueOf(session.getAttribute(Const.USER_ROLE)).equals("3")){
				this.professionInfoList = professionInfoService.getProfessionInfo(String.valueOf(session.getAttribute(Const.USER_DEPARTMENT_CODE)));
				this.bjdmbList = bjdmbService.getBjdmb(String.valueOf(session.getAttribute(Const.USER_DEPARTMENT_CODE)),null);
				Page<Thesis> pageList = thesisService.getThesisList(studentName, String.valueOf(session.getAttribute(Const.USER_DEPARTMENT_NAME)), ZYDM, XZB, DQSZJ, pageNumber);
				mv.addObject("currentPage", pageNumber);
				mv.addObject("bjdmbList",bjdmbList);
				mv.addObject("professionInfoList",professionInfoList);
				mv.addObject("ZYDM", ZYDM);
				mv.addObject("XZB", XZB);
				mv.addObject("totalPage", pageList.getTotalPage());
				mv.addObject("totalCount", pageList.getTotalCount());
				mv.addObject("paperList", pageList.getResultList());
			}else {
				this.bjdmbList = bjdmbService.getBjdmbByTh(String.valueOf(session.getAttribute(Const.SESSION_ACCOUNT)));
				Page<Thesis> pageList = thesisService.getThesisByThList(studentName, String.valueOf(session.getAttribute(Const.SESSION_ACCOUNT)), XZB, DQSZJ, pageNumber);
				mv.addObject("currentPage", pageNumber);
				mv.addObject("bjdmbList",bjdmbList);
				mv.addObject("professionInfoList",professionInfoList);
				mv.addObject("ZYDM", ZYDM);
				mv.addObject("XZB", XZB);
				mv.addObject("totalPage", pageList.getTotalPage());
				mv.addObject("totalCount", pageList.getTotalCount());
				mv.addObject("paperList", pageList.getResultList());
			}
			String[] gradeList = StringUtil.getCurrentGrades();
			mv.addObject("gradeList", gradeList);
			mv.addObject("DQSZJ", DQSZJ);
			mv.addObject("studentName", studentName);
		} catch (Exception ex) {
			ex.printStackTrace();
		}
		return mv;
	}
	@RequestMapping("/departmentInfo.do")
	@ResponseBody
	public JSONObject departmentInfo(@RequestParam("XYMC")String  XYMC) {
		JSONObject json = new JSONObject();
		DepartmentInfo departmentInfo=	departmentInfoService.getDepartmentInfo(XYMC);
		if (departmentInfo!=null) {
			this.professionInfoList = professionInfoService.getProfessionInfo(departmentInfo.getXYDM());
			this.bjdmbList = bjdmbService.getBjdmb(departmentInfo.getXYDM(),null);
		}else {
			this.professionInfoList = professionInfoService.getProfessionInfoList();
			this.bjdmbList = bjdmbService.getBjdmbList();
		}
		json.put("bjdmbList", bjdmbList);
		json.put("professionInfoList", professionInfoList);
		return json;
	}
	@RequestMapping("/professionInfo.do")
	@ResponseBody
	public JSONObject professionInfo(@RequestParam("ZYDM")String  ZYDM,@RequestParam("XYMC")String  XYMC) {
		JSONObject json = new JSONObject();
		DepartmentInfo departmentInfo=	departmentInfoService.getDepartmentInfo(XYMC);
		if (departmentInfo!=null) {
		this.bjdmbList = bjdmbService.getBjdmb(departmentInfo.getXYDM(),ZYDM);
	
		}else {
			this.bjdmbList = bjdmbService.getBjdmb(null,ZYDM);
		}	
		json.put("bjdmbList", bjdmbList);
		return json;
	}
	/**?
	 * 下载论文
	 * @param studentNumber
	 * @param request
	 * @param response
	 */
	@RequestMapping("/DownloadThesis.do")
	public void DownloadPaper(@RequestParam String studentNumber,HttpServletRequest request,   HttpServletResponse response) {
			Thesis   thesis= thesisService.getThesisByStudentNumber(studentNumber);
			try {
				request.setCharacterEncoding("UTF-8");
				BufferedInputStream bis = null;  
		        BufferedOutputStream bos = null;  
			if (thesis!= null) {
				String realPath = getSession().getServletContext().getRealPath("/")+ thesis.getRoute();// 获取要下载的文件的绝对路径
				String fileName = realPath.substring(realPath.lastIndexOf("\\") + 1);// 获取要下载的文件名
				// 设置content-disposition响应头控制浏览器以下载的形式打开文件，中文文件名要使用URLEncoder.encode方法进行编码，否则会出现文件名乱码
				InputStream in = new FileInputStream(realPath);// 获取文件输入流
				 //获取文件的长度
		        long fileLength = new File(realPath).length();  
		        //设置文件输出类型
		        response.setContentType("application/octet-stream");  
		        response.setHeader("Content-disposition", "attachment; filename="  
		                + new String(fileName.getBytes("utf-8"), "ISO8859-1")); 
		        //设置输出长度
		        response.setHeader("Content-Length", String.valueOf(fileLength));  
		        //获取输入流
		        bis = new BufferedInputStream(new FileInputStream(realPath));  
		        //输出流
		        bos = new BufferedOutputStream(response.getOutputStream());  
		        byte[] buff = new byte[2048];  
		        int bytesRead;  
		        while (-1 != (bytesRead = bis.read(buff, 0, buff.length))) {  
		            bos.write(buff, 0, bytesRead);  
		        }  
		        //关闭流
		        bis.close();  
		        bos.close();  
		        }
				thesis.setWhetherMarking(1);
				thesisService.whetherMarking(thesis);
			}catch(Exception e){
                  e.printStackTrace();
          }
	}
	/**?
	 * 我的毕业论文
	 * @return
	 */
	@RequestMapping("/my_thesis_list.do")
	public ModelAndView myThesisList() {
		ModelAndView mv = new ModelAndView("my_thesis");
		HttpSession session = getSession();
		List<Thesis> pageList =thesisService.getMyThesisList(String.valueOf(session.getAttribute(Const.SESSION_ACCOUNT)));
		mv.addObject("paperList", pageList);
		Thesis thesis =thesisService.getThesisByStudentNumber(String.valueOf(session.getAttribute(Const.SESSION_ACCOUNT)));
		if (thesis==null) {
			mv.addObject("add", 0);
		}else {
			mv.addObject("add", 1);
		}
		return mv;
	}
	/**?
	 * 上传标题
	 * @return
	 */
	@RequestMapping("/thesis_add.do")
	public ModelAndView thesisAdd() {
		ModelAndView mv = new ModelAndView("my_thesis_add");
		return mv;
	}
	@RequestMapping("/uploadThesis.do")
	@ResponseBody
	public net.sf.json.JSONObject uploapThesis(@RequestParam("fileAdd") MultipartFile fileAdd,@RequestParam("thesisTitle")String thesisTitle ){
		net.sf.json.JSONObject json = new net.sf.json.JSONObject();
		HttpSession session = getSession();
		StudentInfo studentInfo = studentInfoService.getStudentInfoByXH(String.valueOf(session.getAttribute(Const.SESSION_ACCOUNT)));
		Thesis thesis = new Thesis();
		thesis.setThesisTitle(thesisTitle);
		if (fileAdd.isEmpty()==false) {
			String result = FileUpload.File(fileAdd);
			thesis.setRoute(result);
		}
		thesis.setDQSZJ(String.valueOf(studentInfo.getDQSZJ()));
		thesis.setStudentName(studentInfo.getXM());
		thesis.setTime(StringUtil.getStrDateTime());
		thesis.setStudentNumber(studentInfo.getXH());
		thesis.setWhetherMarking(0);
		thesis.setTeacherNumber(studentInfo.getSchoolTeacher());
		thesis.setXY(studentInfo.getXY());
		thesis.setXZB(studentInfo.getXZB());
		thesis.setZYDM(studentInfo.getZYDM());
		int rel =thesisService.addThesis(thesis);
		json.put("result", rel>0?"success":"error");
		return json;
	}
	/**?
	 * 删除
	 * @param Id
	 * @return
	 */
		@RequestMapping("/delete.do")
		@ResponseBody
		public JSONObject delPaper(@RequestParam String studentNumber){
			JSONObject json = new JSONObject();
			int  rel= thesisService.delThesis(studentNumber);
			json.put("result", rel > 0 ?"success":"error");
			 return json; 
		}
		/**?
		 * 编辑论文
		 * @return
		 */
		@RequestMapping("/thesis_edit.do")
		public ModelAndView thesisEdit() {
			ModelAndView mv = new ModelAndView("my_thesis_edit");
			HttpSession session = getSession();
			Thesis thesis = thesisService.getThesisByStudentNumber(String.valueOf(session.getAttribute(Const.SESSION_ACCOUNT)));
			mv.addObject("thesis", thesis);
			return mv;
		}
		@RequestMapping("/editThesis.do")
		@ResponseBody
		public net.sf.json.JSONObject editThesis(@RequestParam("fileAdd") MultipartFile fileAdd,@RequestParam("thesisTitle")String thesisTitle ){
			net.sf.json.JSONObject json = new net.sf.json.JSONObject();
			HttpSession session = getSession();
			Thesis thesis = thesisService.getThesisByStudentNumber(String.valueOf(session.getAttribute(Const.SESSION_ACCOUNT)));
			thesis.setThesisTitle(thesisTitle);
			if (fileAdd.isEmpty()==false) {
				String result = FileUpload.File(fileAdd);
				thesis.setRoute(result);
			}
			int rel =thesisService.updateThesis(thesis);
			json.put("result", rel>0?"success":"error");
			return json;
		}
}